<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="100px">
      <el-form-item label="叉车牌照" prop="licensePlate">
        <el-input
          v-model="queryParams.licensePlate"
          placeholder="请输入叉车牌照"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="年检日期" prop="yearlyInspectionDate">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="类型" prop="delFlag" v-if="this.queryParams.delFlag=='1' || this.queryParams.delFlag=='2' || this.queryParams.delFlag == '3'">
        <el-select v-model="queryParams.delFlag" placeholder="请选择类型"  size="small">
          <el-option label="全部" value="1" />
          <el-option label="即将超期" value="2" />
          <el-option label="已超期" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属经营户" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入所属经营户"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属场站" prop="stationName">
        <el-input
          v-model="queryParams.stationName"
          placeholder="请输入所属场站"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
     <!-- <el-col :span="1.5" v-if="station_btn">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['ledger:forklift:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="station_btn">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['ledger:forklift:import']"
        >导入</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="forkliftList" :max-height="tableHeight" @selection-change="handleSelectionChange">
      <el-table-column label="所属经营户" align="left" prop="companyName" width="300"/>
      <el-table-column label="叉车牌照" align="center" prop="licensePlate" />
      <el-table-column label="年检日期" align="center" prop="yearlyInspectionDate">
        <template slot-scope="scope">
          <span>{{ scope.row.yearlyInspectionDate | dateString('YYYY-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="yearlyInspectionDate" v-if="this.queryParams.delFlag == '1' || this.queryParams.delFlag == '2' || this.queryParams.delFlag == '3'">
        <template slot-scope="scope">
          <span >{{ timeFormat(scope.row.yearlyInspectionDate)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属场站" align="left" prop="stationName" width="300" v-if="!station_btn"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >详情</el-button>
          <!--<el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['ledger:forklift:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['ledger:forklift:remove']"
          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改叉车台账对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属经营户" prop="companyName">
          <el-input :disabled="true" v-model="form.companyName" placeholder="请选择所属经营户" style="width:85%;"/>
          <div @click="selectBussiness()" class="to-search" style="float:right;margin-right:20px;">
            <span class="el-icon-search"></span>
          </div>
        </el-form-item>
        <el-form-item label="叉车牌照" prop="licensePlate">
          <el-input v-model="form.licensePlate" placeholder="请输入叉车牌照" maxlength="20"  show-word-limit/>
        </el-form-item>
        <el-form-item label="年检日期" prop="yearlyInspectionDate">
          <el-date-picker clearable size="small" style="width: 100%"
            v-model="form.yearlyInspectionDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择年检日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入型号" maxlength="20"  show-word-limit/>
        </el-form-item>
        <el-form-item label="出厂编号" prop="factoryNumber">
          <el-input v-model="form.factoryNumber" placeholder="请输入出厂编号" maxlength="20"  show-word-limit/>
        </el-form-item>
        <el-form-item label="安装地点" prop="installationSite">
          <el-input v-model="form.installationSite" placeholder="请输入安装地点" maxlength="50"  show-word-limit/>
        </el-form-item>
        <el-form-item label="上传图片">
          <el-upload
            :multiple="true"
            accept=".jpg, .png, .gif, .bmp, .jpeg"
            :headers="uploadImg.headers"
            :action="uploadImg.url"
            :file-list="form.imgList"
            list-type="picture-card"
            :limit="uploadImg.limit"
            :before-upload="beforeImageUpload"
            :on-exceed="exceedFile"
            :on-success="handlePictureSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png/bmp/jpeg文件，且不超过10M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>

    <!--    详情-->
    <el-dialog :title="title" :visible.sync="openView"  width="600px">
      <el-form ref="form" :model="form"  label-width="100px">
        <el-form-item label="所属经营户:" prop="businessId">{{form.companyName}}</el-form-item>
<!--        <el-form-item label="营业执照号:" prop="businessId">{{form.businessLicenseNo}}</el-form-item>-->
        <el-form-item label="叉车牌照:" prop="licensePlate">{{form.licensePlate}}</el-form-item>
        <el-form-item label="年检日期:" prop="yearlyInspectionDate">{{ form.yearlyInspectionDate | dateString('YYYY-MM-DD') }}</el-form-item>
        <el-form-item label="型号:" prop="model" v-if="form.model">{{form.model}}</el-form-item>
        <el-form-item label="出厂编号:" prop="factoryNumber" v-if="form.factoryNumber">{{form.factoryNumber}}</el-form-item>
        <el-form-item label="安装地点:" prop="installationSite" v-if="form.installationSite">{{form.installationSite}}</el-form-item>
        <el-form-item label="图片:" class="img" prop="imgList" v-if="form.imgList && form.imgList.length > 0 ">
          <ul>
            <li v-for="img in form.imgList" style="text-align: center;">
              <el-image :preview-src-list="srcList" :src="img.url" style="width: 100px;height:100px;"></el-image>
            </li>
          </ul>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openView = false">关 闭</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择经营户" :visible.sync="openBusiness" width="800px">
      <el-form :model="queryBusinessParams" ref="queryBusinessForm" :inline="true" label-width="68px">
        <el-form-item label="名称" prop="companyName" :width="150">
          <el-input
            v-model="queryBusinessParams.companyName"
            placeholder="请输入名称"
            clearable
            size="small"
            @keyup.enter.native="handleBusinessQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleBusinessQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="businessLoading" ref="bussinessTable" :data="businessList" :max-height="tableHeight2" @selection-change="handleBusinessSelectionChange" :reserve-selection="false">
        <el-table-column type="selection" width="55" align="center" prop="id" />
        <el-table-column label="企业名称" align="left" prop="companyName" />
        <el-table-column label="法人" align="center" prop="legalPerson" :width="120" />
        <el-table-column label="联系电话" align="center" prop="telephone" :width="200"/>
      </el-table>

      <pagination
        v-show="totalBusiness>0"
        :total="totalBusiness"
        :page.sync="queryBusinessParams.pageNum"
        :limit.sync="queryBusinessParams.pageSize"
        @pagination="selectBusinessList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sbumitBusiness">确 定</el-button>
        <el-button @click="openBusiness=false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 叉车导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的叉车数据
          <el-link type="info" style="color:blue;" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listForklift, getForklift, delForklift, addForklift, updateForklift, exportForklift, importTemplate } from "@/api/ledger/forklift";
import { listAccount } from "@/api/ledger/account";
import { getToken } from "@/utils/auth";
export default {
  name: "Forklift",
  data() {
    return {
      // 遮罩层
      loading: true,
      businessLoading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      totalBusiness: 0,
      // 叉车台账表格数据
      forkliftList: [],
      accountList: [],
      businessList: [],
      srcList: [],
      dateRange: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openView: false,
      openBusiness: false,
      station_btn: false,
      businessId: undefined,
      tableHeight: window.innerHeight - 275,
      tableHeight2: window.innerHeight - 450,
      // 上传图片参数
      uploadImg: {
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/upload",
        //  文件个数
        limit: 5
      },
      // 叉车导入参数
      upload: {
        // 是否显示弹出层（叉车导入）
        open: false,
        // 弹出层标题（叉车导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ledger/forklift/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        businessId: undefined,
        stationName: undefined,
        companyName: undefined,
        licensePlate: undefined,
        yearlyInspectionDate: undefined,
        delFlag: undefined,
      },
      queryBusinessParams: {
        pageNum: 1,
        pageSize: 10,
        companyName: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        companyName: [
          { required: true, message: "请选择经营户", trigger: "blur" }
        ],
        licensePlate: [
          { required: true, message: "牌照不能为空", trigger: "blur" }
        ],
        yearlyInspectionDate: [
          { required: true, message: "年检日期不能为空", trigger: "blur" }
        ],
      },
      dialogImageUrl: '',
      dialogVisible: false
    };
  },
  created() {
    const stationId = this.$route.params && this.$route.params.stationId;
    this.queryParams.stationId=stationId;
    const stationName = this.$route.params && this.$route.params.stationName;
    this.queryParams.stationName=stationName;
    const companyName = this.$route.params && this.$route.params.companyName;
    this.queryParams.companyName=companyName;
    const businessId = this.$route.params && this.$route.params.businessId;
    const  delFlag=this.$route.params && this.$route.params.delFlag;
    this.queryParams.delFlag = delFlag;
    this.getList();
    this.getAccountList();

    const roles = this.$store.getters && this.$store.getters.roles;
    for (let rol of roles){
      if ('station'==rol || 'hs_station'==rol){
        this.station_btn=true;
      }
    }
  },
  methods: {
    /** 查询叉车台账列表 */
    getList() {
      this.loading = true;
      listForklift(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.forkliftList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getAccountList(){
      let _param={
        pageNum: 1,
        pageSize: 10000,
        stationId: undefined,
      }
      listAccount(_param).then(res => {
        this.accountList = res.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        businessId: undefined,
        companyName: undefined,
        licensePlate: undefined,
        yearlyInspectionDate: undefined,
        model: undefined,
        factoryNumber: undefined,
        installationSite: undefined,
        delFlag: undefined,
        createTime: undefined,
        createId: undefined,
        updateTime: undefined,
        updateId: undefined,
        remark: undefined,
        imgList: [],
        imgs:[],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    handleBusinessQuery(){
      this.queryBusinessParams.pageNum = 1;
      this.selectBusinessList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    handleBusinessSelectionChange(selection) {
      if(selection.length > 1){
        this.$refs.bussinessTable.clearSelection();
        this.$refs.bussinessTable.toggleRowSelection(selection.pop());
      }else{
        this.selectBusiness = selection.pop();
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      if(this.businessId != undefined){
        this.form.companyName = this.queryParams.companyName;
        this.form.businessId = this.businessId;
      }
      this.open = true;
      this.title = "添加叉车信息";
    },
    /** 详情 **/
    handleView(row) {
      getForklift(row.id).then(response => {
        this.form = response.data;
        const imgs = [];
        this.form.imgList.map(function (item) {
          imgs.push(item.url);
        });
        this.srcList = imgs;
        this.openView = true;
        this.title = "叉车详情";
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getForklift(id).then(response => {
        this.form = response.data;
        const imgs = [];
        this.form.imgList.map(function (item) {
          imgs.push(item.url);
        });
        this.form.imgs = imgs;
        this.open = true;
        this.title = "修改叉车信息";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateForklift(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          } else {
            addForklift(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              } else {
                this.msgError(response.msg);
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除该条叉车的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delForklift(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有叉车台账数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportForklift(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "叉车导入";
      this.upload.open = true;
    },
    timeFormat(value){
      if (new Date(value).getTime()>new Date().getTime()){
        return "即将超期"
      }
      return "已超期"
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    beforeImageUpload(file){
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 10MB!')
        return false
      }
    },
    exceedFile(files, fileList) {
      let msg = `最多只能上传${this.upload.limit}个图片`;
      this.$message.warning(msg)
    },
    //图片上传
    handleRemove(file, fileList) {
      this.form.imgs.splice(this.form.imgs.indexOf(file.url),1);
      // this.form.imgList.splice(this.form.imgList.indexOf(file.url),1);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handlePictureSuccess(response, file) {
      this.form.imgs.push(response.fileName);
      // this.form.imgList.push({
      //   url: response.fileName
      // });
    },
    selectBussiness(){
      this.resetForm("queryBusinessForm");
      this.selectBusinessList();
      this.openBusiness = true;
    },
    selectBusinessList() {
      this.businessLoading = true;
      listAccount(this.queryBusinessParams).then(response => {
        this.businessList = response.rows;
        this.totalBusiness = response.total;
        this.businessLoading = false;
      });
    },
    sbumitBusiness(){
      if(this.selectBusiness == undefined){
        this.msgError("请选择经营户");
      }else{
        this.openBusiness = false;
        this.form.companyName = this.selectBusiness.companyName;
        this.form.businessId = this.selectBusiness.id;
      }
    },
  }
};
</script>
<style>
  .people-to {
    width: 100%;
    display: flex;
    justify-content: space-around;
    align-items: flex-start;
  }
  .to-search{
    width:40px;
    height: 36px;
    line-height:36px;
    text-align:center;
    background: #1890ff;
    color: #fff;
  }
  .img ul{
    padding: 0;
  }
  .img ul li{
    float:left;
    width:20%;
    list-style:none;
    width: 100px;
    margin-right: 2%;
  }
  #queryBusinessForm td{
    height: 30px !important;
  }
  .el-upload__tip{
    font-size: 14px;
  }
</style>
